package com.jacky.util;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import io.flutter.plugin.common.PluginRegistry;

/**
 * 权限处理
 */
public class PermissionUtil {
    private static final int CAMERA_REQUEST_ID = 9600;

    public interface PermissionsRegistry {
        void addListener(PluginRegistry.RequestPermissionsResultListener handler);
    }

    public interface ActivityForResultRegistry {
        void addListener(PluginRegistry.ActivityResultListener handler);
    }


    public static void requestPermissions(
            Activity activity,
            PermissionsRegistry permissionsRegistry,
            OnOcrRectErrorCallback callback) {
        if (!hasCameraPermission(activity)) {
            permissionsRegistry.addListener((requestCode, permissions, grantResults) -> {
                if(requestCode != CAMERA_REQUEST_ID) return false;
                if(grantResults[0] != PackageManager.PERMISSION_GRANTED){
                    callback.callback("cameraPermission","相机权限未开启");
                }
                //permissions grant
                callback.callback(null, null);
                return true;
            });
            ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, CAMERA_REQUEST_ID);
        } else {
            // Permissions already exist. Call the callback with success.
            callback.callback(null, null);
        }
    }


    private static boolean hasCameraPermission(Activity activity) {
        return ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
    }
}
